package dbsharding

import (
	"fmt"
	"gitee.com/youbeiwuhuan/gin-practice/go-gorm2-sharding/entity"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
)

// 分库分表

type ShardingDbPolicy struct {
}

func (ShardingDbPolicy) Resolve(connPools []gorm.ConnPool) gorm.ConnPool {
	return connPools[0]
}

func RunDbSharding() {
	dsn := "root:fan1988@tcp(127.0.0.1:3306)/sharding_jdbc0?charset=utf8mb4&parseTime=True&loc=Local"
	dsnRead := "root:fan1988@tcp(127.0.0.1:3306)/sharding_jdbc1?charset=utf8mb4&parseTime=True&loc=Local"

	conn := mysql.Open(dsn)
	connRead := mysql.Open(dsnRead)

	db, err := gorm.Open(conn, &gorm.Config{})
	if err != nil {
		panic(err)
	}

	// 为主库设置从库
	db.Use(dbresolver.Register(dbresolver.Config{
		Replicas:          []gorm.Dialector{connRead},
		TraceResolverMode: true, // 启用跟踪
		// sources/replicas load balancing policy
		Policy: dbresolver.RandomPolicy{},
	}))

	// 默认走从库
	o := entity.Order{}
	db.Raw("select * from t_order where order_id = ? limit 1", 228620604381593600).Scan(&o)
	fmt.Printf("-----1------%+v \n", o)
}
